package com.zdzx.controller.admin.content;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.model.dic.FileType;
import com.zdzx.service.OSSService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "文件上传")
@RestController
@RequestMapping("/admin")
public class UploadController {

  @Autowired
  private OSSService ossService;

  /**
   * 实现文件上传
   */
  @ApiOperation(value = "公共文件上传", notes = "")
  @PostMapping(value = "/upload")
  public Result<String> upload(@RequestParam("type") String type,
                               @RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
      return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
    } else if (!FileType.hasKey(type)) {
      return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
    }
    String bucketName = "static";
    Result<String> upload = ossService.upload(bucketName, type, file);
    return upload;
  }

  @ApiOperation(value = "私有文件上传", notes = "")
  @PostMapping(value = "/pupload/{tenantId}")
  public Result<String> upload(
    @PathVariable("tenantId") String tenantId,
    @RequestParam("type") String type,
    @RequestParam("file") MultipartFile file) {
    if (StringUtils.isEmpty(tenantId)) {
      return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "租户不存在", null);
    } else if (file.isEmpty()) {
      return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
    } else if (!FileType.hasKey(type)) {
      return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
    }
    Result<String> upload = ossService.upload(tenantId, type, file);
    return upload;
  }

  @ApiOperation(value = "文件上删除", notes = "")
  @DeleteMapping("/upload/{url}")
  public Result<String> removeFile(@PathVariable("url") String url) {
    return ossService.removeFile(url);
  }
}
